package com.byght.bygsystem.service;

import com.byght.bygsystem.model.Role;
import com.byght.bygsystem.repository.RoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class RoleService {
    @Autowired
    private RoleRepository roleRepository;

    // 根据角色 ID 查找角色
    public Role getRoleById(Long roleId) {
        return roleRepository.findById(roleId)
                .orElseThrow(() -> new RuntimeException("Role not found with id " + roleId));
    }

    // 创建角色
    public Role createRole(Role role) {
        return roleRepository.save(role);
    }

    // 更新角色
    public Role updateRole(Long roleId, Role updatedRole) {
        Role existingRole = getRoleById(roleId);
        existingRole.setName(updatedRole.getName());
        existingRole.setDescription(updatedRole.getDescription());
        return roleRepository.save(existingRole);
    }

    // 删除角色
    public void deleteRole(Long roleId) {
        if (!roleRepository.existsById(roleId)) {
            throw new RuntimeException("Role not found with id " + roleId);
        }
        roleRepository.deleteById(roleId);
    }

    public List<Role> getAllRoles() {
        return roleRepository.findAll();
    }
}
